"""
Create a binding for a swf file.
"""
import argparse
import flexutils
try:
    from io import BytesIO
except ImportError:
    from StringIO import StringIO as BytesIO
import logging
import os
import subprocess
import sys
import xml.etree.cElementTree as xml


class SwfStruct(object):
    def __init__(self, flex_home):
        self.flex_home = flex_home
        self.swfdump_path = flexutils.get_flex_swfdump_path(flex_home)
        flexutils.verify_swfdump(self.swfdump_path)
    
    def generate_as3_binding(self, swf_filepath):
        pass
    
    def get_swf_classnames(self, swf_path):
        XML_NAMESPACE = "{http://macromedia/2003/swfx}"
        classnames = []
        cmd = [self.swfdump_path, '-noactions', '-nofunctions', '-noglyphs', swf_path]
        logging.info("cmd: %s", " ".join(cmd))
        proc = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)
        outdata, errdata = proc.communicate()
        if errdata:
            logging.error("Error running swfdump: %s", errdata)
        else:
            try:
                outdata = outdata.decode('cp1252').encode('utf8')   # handle invalid xml - copyright symbol breaks parsing
            except UnicodeDecodeError:
                pass
            tree = xml.parse(BytesIO(outdata))
            symbol_list = tree.findall("%sSymbolClass/%sSymbol" % (XML_NAMESPACE, XML_NAMESPACE))
            if symbol_list:
                for symbol in symbol_list:
                    if "className" in symbol.attrib:
                        classnames.append(symbol.attrib["className"])
                    else:
                        logging.error("Could not find className attribute in node: %s %s", symbol.tag, symbol.attrib)
            else:
                logging.warn("no symbols found in swf: %s", swf_path)
        classnames.sort()
        return classnames


def get_args():
    parser = argparse.ArgumentParser(description='Parse swf files and create a binding.')
    parser.add_argument('--flex-sdk', dest='flex_sdk_path',
                        default=os.environ['FLEX_HOME'] if 'FLEX_HOME' in os.environ else None,
                        help='Path to the Flex SDK to use.  In not provided, use the FLEX_HOME environment variable.')
    parser.add_argument('swf_files', nargs='+', help='List of one or more swf file paths.')
    args = parser.parse_args()
    if not args.flex_sdk_path:
        print('FLEX_HOME must be specified as an option or as an environment variable.')
        parser.print_help()
        sys.exit()
    return args

def main():
    args = get_args()
    flex_sdk_path = os.path.expanduser(args.flex_sdk_path)
    swfparser = SwfStruct(flex_sdk_path)
    for swf_filepath in args.swf_files:
        swf_filepath = os.path.expanduser(swf_filepath)
        print(swfparser.get_swf_classnames(swf_filepath))

if __name__=='__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()
